﻿using Base.Infrastructure.Dto.Request.Usert;
using Base.Infrastructure.Dto.Response;
using Base.Infrastructure.EFCore.MySql;
using Base.Infrastructure.IOC;
using Base.Infrastructure.Tools;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Base.Service.Instance
{
    public class UsertService : BaseService, Base.Service.Interface.IUsertService
    {
        private readonly UsertIOC _usertIOC;

        public UsertService(UsertIOC usertIOC, IConfiguration configuration)
        {
            _usertIOC = usertIOC;
        }

        /// <summary>
        /// 添加用户
        /// </summary>
        /// <returns></returns>
        private bool AddUsert(Usert usert)
        {
            _usertIOC._usertService.Add(usert);
            return _usertIOC._usertService.SaveChanges() > 0;
        }

        /// <summary>
        /// （登录）通过UisBan判断用户是否被禁用，再通过verify判断随机数是否正确，并给Uaccount绑定openid
        /// </summary>
        /// <param name="Uaccount"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ApiResult CheckUsert(string Uaccount, string Code, string Openid, string verify)
        {
            //生成随机码//每次登录获取数据库随机码，登录成功后更改数据库随机码
            string Letters = "1,2,3,4,5,6,7,8,9,0,A,B,C,D,E,F,G,H,I,H,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
            var array = Letters.Split(",");
            var random = new Random();
            string randomcode = "";
            for (int i = 0; i < 5; i++)
            {
                randomcode += array[random.Next(array.Length)];
            }

            //找到用户绑定openid并更换随机码
            var ai = _usertIOC._usertService.QueryAll(d => d.Uaccount == Uaccount);
            if (ai.Any())
            {
                //登录（给用户绑定openid）
                var ia = ai.Single();
                if (ia.UisBan == "0")
                {
                    if (ia.Verification == verify)
                    {
                        ia.Uopenid = Openid;
                        ia.Ucode = Code;
                        ia.Verification = randomcode;//更换随机码
                        _usertIOC._usertService.Update(ia);
                        _usertIOC._usertService.SaveChanges();

                        return GetResult(1, "登录成功");
                    }
                    else
                    {
                        return GetResult(-1, "验证码错误");
                    }
                }
                else 
                {
                    return GetResult(-1, "您的账号不可用");
                }
            }
            else 
            {
                return GetResult(-1, "验证码错误");
            }
        }

        /// <summary>
        /// 判断用户是否登录,,并返回该用户手机号，状态和班级
        /// </summary>
        /// <param name="Openid"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ApiResult CheckOpenid(string Openid)
        {
            var ai = _usertIOC._usertService.QueryAll(d => d.Uopenid == Openid);
            if (ai.Any())
            {
                var ia = ai.Single();
                var ai2 = new
                {
                    uid=ia.Uid,
                    Uaccount = ia.Uaccount,
                    UisBan=ia.UisBan,
                    Ucid = ia.Ucid,
                    Uname=ia.Uname
                };
                return GetResult(1, "当前用户已登录", data: ai2);

            }
            return GetResult(-1, "用户当前未登录");
        }

        /// <summary>
        /// 用户解绑openid
        /// </summary>
        /// <param name="Uaccount"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ApiResult TuichuOpenid(string Uaccount)
        {
            var ai = _usertIOC._usertService.QueryAll(d => d.Uaccount == Uaccount).Single();
            ai.Uopenid = "NULL";
            _usertIOC._usertService.Update(ai);
            _usertIOC._usertService.SaveChanges();
            return GetResult(1, "已退出");
        }

        /// <summary>
        /// （获取随机码）根据UAccount获取数据库验证码，如果没有该用户则添加用户并返回随机码
        /// </summary>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public ApiResult verification(string UAccount)
        {
            //生成随机码
            string Letters = "1,2,3,4,5,6,7,8,9,0,A,B,C,D,E,F,G,H,I,H,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z";
            var array = Letters.Split(",");
            var random = new Random();
            string randomcode = "";
            for (int i = 0; i < 5; i++)
            {
                randomcode += array[random.Next(array.Length)];
            }

            //判断用户是否存在（存在则放回随机码/不存在则添加用户并返回随机码）
            var ai = _usertIOC._usertService.QueryAll(d => d.Uaccount == UAccount);
            if (ai.Any())
            {
                //存在则返回随机码
                var ia = ai.Single();
                return GetResult(1, data: ia.Verification);
            }
            else
            {
                //不存在 ，添加用户并返回随机码
                string id = Config.GUID();
                this.AddUsert(new Usert
                {
                    Uid = id,
                    Uname = "",
                    Uaccount = UAccount,
                    Ucode = null,
                    Uopenid = null,
                    Verification = randomcode,//添加随机码
                    Ucid=null,
                    UisBan="0"
                });
                return GetResult(1, data: randomcode);
            }
        }
    }
}
